<template>
  <el-card class="box-card">
    <!-- 顶部标题 -->
    <div slot="header" class="clearfix">
      <!-- 使用传递过来的路径参数和普通参数 -->
      <span>上传视频 / 课程ID：{{courseId}} / 课时ID：{{lessonId}}</span>
    </div>
    <el-form label-width="80px">
      <!-- 添加封面 -->
      <el-form-item label="添加封面">
        <input type="file" ref="img">
      </el-form-item>
      <!-- 添加视频 -->
      <el-form-item label="添加视频">
        <input type="file" ref="video">
      </el-form-item>
      <el-form-item label="上传进度"  v-if="uploading">
        <el-progress :percentage="uploadProgress" :text-inside="true" :stroke-width="30"  style="width: 300px"></el-progress>
      </el-form-item>
      <el-form-item label="转码进度"  v-if="transcoding">
        <el-progress :percentage="transcodingProgress" :text-inside="true" :stroke-width="30" style="width: 300px"></el-progress>
      </el-form-item>
      <el-button>返回</el-button>
      <!-- 开始上传按钮添加点击事件 -->
      <el-button type="primary" @click="beginUpload">开始上传</el-button>
    </el-form>
  </el-card>
</template>

<script>
/* eslint-disable*/
// 引入封装的四个阿里云相关接口呀
import {
  aliyunImagUploadAddressAdnAuth,
  aliyunVideoUploadAddressAdnAuth,
  aliyunTransCode,
  aliyunTransCodePercent
} from '@/services/aliyun-upload'
export default {
  name: 'uploadVideo',
  // courseId - 路径参数
  props: ['courseId'],
  data () {
    return {
      // 课时id，通过参数获取
      lessonId: this.$route.query.lessonId,
      // 阿里云上传SDK
      uploader: null,
      // 图片地址
      imageURL: '',
      // 视频id
      videoId: null,
      // 转码进度
      transcodingProgress: 0,
      // 转码状态
      transcoding: false,
      // 上传进度
      uploadProgress: 0,
      // 上传状态
      uploading: false
    }
  },
  // 生命周期钩子函数
  created () {
    // 初始化上传
    this.initAliyun()
  },
  methods: {
    // 开始上传按钮点击事件
    beginUpload () {
      // 重置所有状态和进度
      this.imageURL= ''
      this.videoId= null
      this.transcodingProgress= 0
      this.uploadProgress= 0
      // 将图片和视频添加到上传列表，使用ref获取视频和图片
      const uploader = this.uploader
      uploader.addFile(this.$refs.img.files[0])
      uploader.addFile(this.$refs.video.files[0])
      // 开始上传
      uploader.startUpload()
    },
    initAliyun () {
      this.uploader = new AliyunUpload.Vod({
        //阿里账号ID，必须有值（这里使用老师提供的账号）
        userId: '1618139964448548',
        //上传到视频点播的地域，默认值为'cn-shanghai'，//eu-central-1，ap-southeast-1
        region: '',
        //分片大小默认1 MB，不能小于100 KB
        partSize: 1048576,
        //并行上传分片个数，默认5
        parallel: 5,
        //网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        //网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        //开始上传
        onUploadstarted: async uploadInfo => {
          this.uploading = true
          // 新建一个变量用于接收凭证信息
          let ressAdnAuth = null
          // 判断文件是图片还是视频
          if (uploadInfo.isImage) {
            // 如果是图片调用图片接口
            const { data } = await aliyunImagUploadAddressAdnAuth()
            if (data.code === '000000') {
              // 获取成功后把凭证信息存起来
              ressAdnAuth = data.data
              // 保存图片地址，后面要使用
              this.imageURL = ressAdnAuth.imageURL
            }
          } else {
            // 如果不是图片那就是视频，调用视频接口
            const { data } = await aliyunVideoUploadAddressAdnAuth({
              // 设置参数
              fileName: uploadInfo.file.name,
              imageUrl: this.imageURL
            })
            if (data.code === '000000') {
              // 如果获取成功同样保存信息
              ressAdnAuth = data.data
              this.videoId = data.data.videoId
            }
          }
          // 设置阿里云凭证
          this.uploader.setUploadAuthAndAddress(
            uploadInfo,
            ressAdnAuth.uploadAuth,
            ressAdnAuth.uploadAddress,
            ressAdnAuth.imageId || ressAdnAuth.videoId)
        },
        //文件上传成功
        onUploadSuccee: function (uploadInfo) {
        },
        //文件上传失败
        onUploadFailed: function (uploadInfo, code, message) {
        },
        //文件上传进度，单位：字节
        onUploadProgress: (uploadInfo, totalSize, loadedPercent) => {
          // 图片不需要进度，所有判断不是图片才输出进度
          if (!uploadInfo.isImage) {
            this.uploadProgress = Math.floor(loadedPercent * 100)
          }
        },
        //上传凭证或STS token超时
        onUploadTokenExpired: function (uploadInfo) {
        },
        //全部文件上传结束
        onUploadEnd: async uploadInfo => {
          // 上传成功后请求转码
          const { data } = await aliyunTransCode({
            lessonId: this.lessonId,
            coverImageUrl: this.imageURL,
            fileId: this.videoId,
            fileName: this.$refs.video.files[0].name
          })
          if (data.code === '000000') {
            // 如果转码申请成功设置转码状态
            this.transcoding = true
            // 设置定时器获取循环转码进度
            const timer = setInterval(async () => {
              // 获取转码进度
              const { data } = await aliyunTransCodePercent(this.lessonId)
              if (data.code === '000000') {
                // 获取成功把转码进度同步给数据
                this.transcodingProgress = data.data
                // 判断转码进度为100%则删除定时器
                if (data.data === 100) clearInterval(timer)
              }
            }, 1000)
          }
        }
      })
    }
  }
}
</script>
